package com.sgb.member.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.material.tabs.TabLayout;
import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMemberLogistics3Binding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.CarManageBean;
import com.sgb.member.ui.adapter.WuLiuMemberAdapter3;
import com.sgb.member.view_model.BusinessLogisticsMode3;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.XCustomTabLayout;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * 会员经营-物流货运-管理车辆
 */
public class BusinessLogisticsFragment3 extends AppLazyFragment implements MemberStatusView.OnChooseListener, XChooseDialog.DialogCallBackImpl {

    @Inject
    public BusinessLogisticsMode3 sModel;
    private FragmentMemberLogistics3Binding mBinding;
    private WuLiuMemberAdapter3<CarManageBean> mAdapter;

    private String oneLevel = "";
    private String mNo1;
    private String mNo2;

    private String cart_length = "";//车长
    private String cart_height = "";//栏高
    private String cart_weight = "";//载重

    private List<CommonPopEntity> list = new ArrayList<>();
    private List<CommonPopEntity> car_lens = new ArrayList<>();
    private List<CommonPopEntity> allCarLenData = new ArrayList<>();//所有车长类型
    private Map<String,List<CommonPopEntity>> mCarLenMap = new HashMap<>();

    public static BusinessLogisticsFragment3 newInstance() {
        BusinessLogisticsFragment3 fragment = new BusinessLogisticsFragment3();
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_member_logistics_3, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        initRecycler();
        initPopup();
        initChooseDialog();
        mBinding.chooseLayout.setOnClickListener(v -> {
            mChooseDialog.initData(mData, mFilters);
            mChooseDialog.showDialog();
        });

    }

    @Override
    protected void onLazyLoad() {
        oneLevel = "";
        sModel.getTabType();
        sModel.getAllCarLen();
        sModel.getCarTypeAndLen(oneLevel);
        sModel.getLanHeightVolume();
        sModel.getWeight();
        sModel.getYear();
        loadOtherData();
        loadData(false);
    }

    public void loadData(boolean isLoadMore) {
        sModel.getFilterSourceList(isLoadMore, oneLevel, mNo1,
                mNo2,cart_length,cart_height,cart_weight);
    }

    public void loadOtherData() {
        if (isListEmpty(PickCateType.TYPE_1)) {
            sModel.carFunctionConfig();
        }
        if (isListEmpty(PickCateType.TYPE_2)) {
            sModel.getWeight();
        }
        if (isListEmpty(PickCateType.TYPE_3)) {
            sModel.getCarTypeAndLen(oneLevel);
        }
    }


    public void setTypeDatas(List<CommonPopEntity> datas) {
        this.list.clear();
        this.list.addAll(datas);
        mBinding.childTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mBinding.childTabLayout.setVisibility(View.VISIBLE);
        for (int i = 0; i < list.size(); i++) {
            mBinding.childTabLayout.addTab(mBinding.childTabLayout.newTab().setText(list.get(i).getTypeName()));
        }
        mBinding.childTabLayout.setNormalColor(R.color.color_title_small);
        mBinding.childTabLayout.addOnTabSelectedListener(list, new XCustomTabLayout.SimpleSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int pos = tab.getPosition();
                oneLevel = list.get(pos).getNo();
                if (pos > 0) {
                    car_lens.clear();
                    car_lens.add(new CommonPopEntity("", "全部"));
                    car_lens.addAll(mCarLenMap.get(list.get(pos).getTypeName()));
                    mBinding.popCartLength.setData(car_lens, cart_length);
                } else {
                    mBinding.popCartLength.setData(allCarLenData, cart_length);
                }
                loadData(false);
            }
        });
    }


    // 更新货物重量（吨）
    public void setWeightData(List<CommonPopEntity> list) {
        mBinding.popLoadWeight.setData(list,cart_weight);
    }

    public void setCarFunctionConfig(List<CommonPopEntity> list){
        addMainEntity(PickCateType.TYPE_1, list);
    }

    // 更新货物重量（吨）
    public void setYearData(List<CommonPopEntity> list) {
          addMainEntity(PickCateType.TYPE_2, list);
    }

    // 更新要求车型（可多选）和要求车长（可多选）
    public void setVolumeData(List<CommonPopEntity> list) {
       mBinding.popCartHeight.setData(list,cart_height);
    }


    // 根据车型设置车长
    public void setCarTypeAndLen(List<CommonPopEntity> data,int flag) {
        if(flag==1){
            allCarLenData.add(new CommonPopEntity("", "全部"));
            allCarLenData.addAll(data);
        }else {
            for (CommonPopEntity entity : data) {
                mCarLenMap.put(entity.getTypeName(),entity.getChildren());
            }
        }
        mBinding.popCartLength.setData(allCarLenData, cart_length);
    }

    /**
     * -------------------------------------initRecycler------------------------------------------
     */
    private void initRecycler() {
        TextView textView = mBinding.emptyView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
        mAdapter = new WuLiuMemberAdapter3(getActivity(), R.layout.item_other_logistics_3, null);
        mAdapter.setOnItemClick(new AdapterOnItemClick<CarManageBean>() {
            @Override
            public void onItemClick(CarManageBean carManageBean, int position) {
                ARouter.getInstance()
                        .build(AppRouteConstant.WuLui.ROUTER_PATH_CAR_INFO)
                        .withLong("carNo", Long.parseLong(carManageBean.getNo()))
                        .navigation();
            }
        });
        mBinding.recyclerView.setAdapter(mAdapter);
    }


    public void closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void showEmpty() {
        closeRecyclerRefreshing();
        mAdapter.clearDatas();
        mBinding.emptyView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<CarManageBean> list, boolean isLoadMore, boolean noMoreData) {
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setNoMore(noMoreData);
        closeRecyclerRefreshing();
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * ------------------------------- Popup ---------------------------------------------
     */
    private void initPopup() {
        mBinding.popCartLength.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popCartHeight.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popLoadWeight.initPopup(mBinding.grayLayout, mBinding.popLine, this);

    }

    @Override
    public void onLoadChooseData(String mKeyName) {

    }

    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        if ("车长".equals(mKeyName)) {
            if (!TextUtils.equals(no, cart_length)) {
                cart_length = entity.getNo();
                loadData(false);
            }
        } else if ("栏高".equals(mKeyName)) {
            if (!TextUtils.equals(no, cart_height)) {
                cart_height = entity.getNo();
                loadData(false);
            }
        } else if ("载重".equals(mKeyName)) {
            if (!TextUtils.equals(no, cart_weight)) {
                cart_weight = entity.getNo();
                loadData(false);
            }
        }
    }


    /**
     * ------------------------------------ 侧滑刷选 ----------------------------------------
     */

    private XChooseDialog mChooseDialog;
    private SparseArray<XChooseEntity> mData = new SparseArray<>();
    // 本地缓存筛选结果
    private SparseIntArray mFilters = new SparseIntArray();
    private SparseArray<String> mNameArray;

    private void initChooseDialog() {
        mNameArray = new SparseArray<>();
        mNameArray.put(PickCateType.TYPE_1, "功能");
        mNameArray.put(PickCateType.TYPE_2, "年限");

        mChooseDialog = new XChooseDialog(getContext(), mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            addMainEntity(key, new ArrayList<>());
        }
    }

    public void showLeftDialog(int type, List<CommonPopEntity> data) {
        mChooseDialog.addEntity(type, data);
        mChooseDialog.showDialog();
    }

    public void addMainEntity(int index, List<CommonPopEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
    }

    private boolean isListEmpty(int catType) {
        return mData.get(catType) != null &&
                (mData.get(catType).getList() == null || mData.get(catType).getList().size() == 0);
    }

    @Override
    public void loadChildData(XChooseEntity entity, int pos) {
    }


    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        mData = CopyUtils.deepPopEntityCopy(data);
        mFilters = map.clone();
        for (int i = 0; i < mData.size(); i++) {
            int key = mData.keyAt(i);
            refreshItemValue(key, mFilters.get(key));
        }
        loadData(false);
    }

    private void refreshItemValue(int key, int value) {
        XChooseEntity entity = mData.get(key);
        String itemNo = entity.getItemNo(value);
        switch (key) {
            case PickCateType.TYPE_1:
                mNo1 = itemNo;
                break;
            case PickCateType.TYPE_2:
                mNo2 = itemNo;
                break;
            default:
                break;
        }
    }

    @Override
    public void reset() {
        mFilters.clear();
        result(mData, mFilters);
        mChooseDialog.initData(mData, mFilters);
        mChooseDialog.showDialog();
    }

    @Override
    public void onCancel() {
        mChooseDialog.initData(mData, mFilters);
    }
}
